from django.contrib.auth.hashers import check_password
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from apps.models import User
from apps.utils.common_function import log_error

from apps.utils.common_response import APIResponse
from apps.views.main.user import make_login_log


def get_token(user):
    refresh = RefreshToken.for_user(user)
    return str(refresh.access_token)


class AdminLogin(APIView):
    def post(self, request, *args, **kwargs):
        username = request.data['username']
        password = request.data['password']
        users = User.objects.filter(username=username).first()
        # 验证哈希密码
        is_correct = check_password(password, users.password)
        if is_correct:
            # role='1','3'-管理员演示账号
            users = User.objects.filter(username=username, role__in=['1', '3'])
            # 不存在的情况

            if not users:
                return APIResponse(msg='当前用户没有访问权限')
            user = users[0]

            data = {
                'username': username,
                'password': password,
                'token': get_token(user)
            }

            print(f'data：{data}')
            make_login_log(request)
            return APIResponse(code=0, msg=f'管理员登录成功', data=data)
        return APIResponse(code=1, msg='用户名或密码错误')


# 创建修改查询用户信息

